package test3;

import java.io.*;
import java.net.Socket;

/**
 * Creat with IntelliJ IDEA
 * Description:
 * User:WZW
 * Date:2022-04-11
 * Time:10:28
 */

public class Client {
    public static void main(String[] args) {
        try {
            Socket socket = new Socket("127.0.0.1",9870);//与服务器进行连接
            // 由Socket对象得到输入输出流，并构造相应的输入输出流对象
            DataOutputStream out = new DataOutputStream(socket.getOutputStream());
            DataInputStream in = new DataInputStream(socket.getInputStream());
            System.out.println("收到服务器的响应："+in.readUTF());

            //要下载的文件
            String fileToDownload = "hello.txt";
            // 将文件名发送给服务器
            out.writeUTF(fileToDownload);

            // 接收文件
            Boolean bool = in.readBoolean();
            if (bool){
                System.out.println(in.readUTF());
                byte[] file = new byte[1024];
                in.read(file);
                //保存文件
                String save = "E:/计算机/JAVA/java/hello.txt";
                try (OutputStream outputStream = new FileOutputStream(save)){
                    outputStream.write(file);
                    outputStream.flush();//刷新缓冲区
                }
                System.out.println("文件接收成功！");
                System.out.println("保存为："+save);
            }else {//文件接收失败
                System.out.println(in.readUTF());
            }

        } catch (IOException e) {
            System.out.println("与客户端连接失败");
        }
    }
}
